<?php
declare (strict_types=1);

namespace app\middleware;


use app\admin\model\LogModel;
use app\admin\services\AdminService;
use app\Request;
use think\Response;

class LogMiddleware implements MiddlewareInterface
{
    /**
     * 日志实时写入缓存，每日定时任务从缓存读取日志，到数据库
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        // TODO: Implement handle() method.
        //当前登录用户的信息,自己实现
        $method = strtolower($request->method());
        if (in_array($method, ['post'])) {
            $is_ajax = $request->isAjax();
            $route = $request->pathinfo();
            $req = ($method == 'get') ? $request->get() : $request->post();
            unset($req['s'], $req['_session']);
            $req_data = $req ? json_encode($req) : '';
            $data = [
                'route' => $route,
                'method' => $method,
                'req_tp' => $is_ajax ? 'ajax' : 'normal',
                'req_data' => $req_data,
                'ip' => $request->ip(),
                'create_time' => date('Y-m-d H:i:s'),
                'host' => $request->domain(),
                'done' => 0,
                'order_time'=>date('Y-m-d H:i:s',(int)$req['timestamp']),
                'order_id'=>json_decode($req['data'])->orderId
            ];

            $row = LogModel::editWithReturn($data);
            $request->log_id = $row->id;
        }
        return $next($request);
    }
}
